#!/usr/bin/env python
# -*- coding: utf-8 -*-

from rest_framework.pagination import PageNumberPagination
from rest_framework.decorators import action
from rest_framework import mixins
from rest_framework import viewsets
from django_filters.rest_framework import DjangoFilterBackend

from apps.case.models import Case
from apps.case.case_result_models import CaseResult
from apps.case.serializers import CaseSerializers, CaseListSerializers, CaseResultSerializers
from utils.rest.views import CustomViewBase
from utils.rest.response import JsonResponse


class CasePagination(PageNumberPagination):
    """
    测试项目列表自定义分页
    """

    # 默认每页显示的个数
    page_size = 10
    # 可以动态改变每页显示的个数
    page_size_query_param = 'limit'
    # 页码参数
    page_query_param = 'page'
    # 最多能显示多少页
    max_page_size = 100


class CaseViewSet(CustomViewBase):
    """
    测试用例
    """
    queryset = Case.objects.all().order_by('-edit_time')
    serializer_class = CaseSerializers
    # 分页
    pagination_class = CasePagination
    filter_backends = (DjangoFilterBackend,)
    filter_fields = ('project',)
    search_fields = ('id', 'case_num', 'name')

    def get_serializer_class(self):
        if self.action == 'list':
            return CaseListSerializers
        else:
            return CaseSerializers

    @action(methods=['post'], detail=True)
    def execute(self, request, pk=None):
        """
        单个用例调试接口
        :param request:
        :param pk:
        :return:
        """
    @action(methods=['get'], detail=False)
    def count(self, request):
        count = Case.objects.count()
        return JsonResponse(data={'count': count}, msg='success', code=200)


class CaseResultViewSet(mixins.ListModelMixin, mixins.CreateModelMixin, viewsets.GenericViewSet):

    queryset = CaseResult.objects.all().order_by('-edit_time')
    serializer_class = CaseResultSerializers
    filter_backends = (DjangoFilterBackend, )
    filter_fields = ('report', )
    pagination_class = CasePagination
    search_fields = ('id', 'name', )
